//
//  ScanViewController.m
//  LoveFreshBeen
//
//  Created by 胡不归是大虾 on 2016/10/17.
//  Copyright © 2016年 魏根. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property(nonatomic,strong)AVCaptureSession* session;
@property(nonatomic,strong)AVCaptureDeviceInput* input;
@property(nonatomic,strong)AVCaptureMetadataOutput* output;
@property(nonatomic,strong)AVCaptureVideoPreviewLayer* preview;
@property(nonatomic,weak) UIImageView* scanLineView;
@property(nonatomic,weak) UIImageView* scanBackGroudView;
@property(nonatomic,assign)CGRect scanRect;
@property(nonatomic,weak) UILabel* tipLable;




@end

@implementation ScanViewController
-(instancetype)init{
    if (self = [ super init]) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //扫描区域
    CGRect scanRect = CGRectMake(ScreenWidth / 3 / 2, (ScreenHeight - 64 -ScreenWidth * 2 / 3) / 2 , ScreenWidth * 2 / 3, ScreenWidth * 2 / 3);
    self.scanRect = scanRect;
    //实例化输出输入对象
    AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError* error;
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (!error) {
        //实例化会话对象
        self.session = [[AVCaptureSession alloc] init];
        [self.session setSessionPreset:AVCaptureSessionPresetHigh];
        self.output = [[AVCaptureMetadataOutput alloc] init];
        //添加输入和输出对象
        [self.session addInput:self.input];
        [self.session addOutput: self.output];
        //设置格式为二维码
        self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
        [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        //限定扫描区域
        self.output.rectOfInterest = CGRectMake(scanRect.origin.y / ScreenHeight, scanRect.origin.x / ScreenWidth, scanRect.size.width / ScreenHeight, scanRect.size.height / ScreenWidth);
        //实例化图层
        self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
        self.preview.frame = self.view.bounds;
        self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [self.view.layer addSublayer:self.preview];
        //创建扫描区域的图片
        UIImageView* scanBG = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"qrcode_bg"]];
        scanBG.frame = scanRect;
        //添加扫描框
        [self.view addSubview:scanBG ];
        //添加扫描线
        UIImageView* scanLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"qrcode_line"]];
        scanLine.frame = CGRectMake(scanRect.origin.x, scanRect.origin.y + 2, scanRect.size.width, 2);
        self.scanLineView = scanLine;
        [self.view addSubview:scanLine];
        //添加遮罩
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(ScreenWidth, ScreenHeight), NO, [UIScreen mainScreen].scale);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(ctx, 0, 0, 0, 0.5);
        //设置渲染范围
        CGContextFillRect(ctx, CGRectMake(0, 0, ScreenWidth, ScreenHeight));
        CGContextClearRect(ctx, scanRect);
        UIImage* cover = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        UIImageView* coverImageView = [[UIImageView alloc] initWithImage:cover];
        [self.view addSubview:coverImageView];
                //开始扫描
        [self.session startRunning];
    }
    else{
        //添加背景图,没有摄像头的时候显示
        UIView* view = [[UIView alloc] initWithFrame:self.view.bounds];
        view.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:view];
        //添加提示标签,没有摄像头的时候显示
        UILabel* tipLable = [[UILabel alloc] init];
        self.tipLable = tipLable;
        tipLable.text = @"没有真机你扫描个蛋啊,换真机试试!";
        [tipLable sizeToFit];
        tipLable.frame = CGRectMake(scanRect.origin.x, CGRectGetMaxY(scanRect)+2, tipLable.bounds.size.width, tipLable.bounds.size.height);
        [self.view addSubview:tipLable];
        //创建扫描区域的图片
        UIImageView* scanBG = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"qrcode_bg"]];
        scanBG.frame = scanRect;
        //添加扫描框
        [self.view addSubview:scanBG ];
        //添加扫描线
        UIImageView* scanLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"qrcode_line"]];
        scanLine.frame = CGRectMake(scanRect.origin.x, scanRect.origin.y + 2, scanRect.size.width, 2);
        self.scanLineView = scanLine;
        [self.view addSubview:scanLine];
        //添加遮罩
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(ScreenWidth, ScreenHeight), NO, [UIScreen mainScreen].scale);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(ctx, 0, 0, 0, 0.5);
        //设置渲染范围
        CGContextFillRect(ctx, CGRectMake(0, 0, ScreenWidth, ScreenHeight));
        CGContextClearRect(ctx, scanRect);
        UIImage* cover = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        UIImageView* coverImageView = [[UIImageView alloc] initWithImage:cover];
        [self.view addSubview:coverImageView];
    }
    
    [self scanLineStartAnimation];

    
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    
    [self addBackButton];
    
}

- (void)addBackButton {
    
    self.title = @"扫描店铺二维码";
    UIButton *back = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    [back setBackgroundImage:[UIImage imageNamed:@"v2_goback"] forState:UIControlStateNormal];
    
    [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];
}


- (void)back {
    
    [self.navigationController popViewControllerAnimated:YES];
    
}



-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count> 0) {
        [self.session stopRunning];
        [self scanLineStopAnimation];
        AVMetadataMachineReadableCodeObject* codeObject = metadataObjects[0];
        NSURL * url = [NSURL URLWithString:codeObject.stringValue];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }
    }
}
#pragma mark--扫描线动画
-(void)scanLineStartAnimation{
    CABasicAnimation* basic = [CABasicAnimation animationWithKeyPath:@"position.y"];
    basic.fromValue = @(self.scanRect.origin.y +2);
    basic.toValue = @(CGRectGetMaxY(self.scanRect) - 2);
    basic.duration = 2.0 ;
    basic.repeatCount = MAXFLOAT ;
    [self.scanLineView.layer addAnimation:basic forKey:nil];
}

-(void)scanLineStopAnimation{
    [self.scanLineView.layer removeAllAnimations];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:254/255.0 green:211/255.0 blue:65/255.0 alpha:1]];
    
}






@end
